package org.papervision3d.materials
{
    import flash.display.MovieClip;
    import flash.display.BitmapData;
    import flash.utils.getDefinitionByName;
    import flash.utils.Dictionary;
    
    // The MovieAssetMaterial class creates a texture from a MovieClip library symbol.
    // The texture can be animated and/or transparent.
    // The MovieClip's content needs to be top left aligned with the registration point.
    // Materials collects data about how objects appear when rendered.
    public class MovieAssetMaterial extends MovieMaterial
    {

        // The MovieAssetMaterial class creates a texture from a MovieClip library id.
        // @param    id                  The linkage name of the MovieClip symbol in the library.
        // @param    transparent         [optional] - If it's not transparent, the empty areas of the MovieClip will be of fill32 color. Default value is false.
        // @param    initObject          [optional] - An object that contains additional properties with which to populate the newly created material.
        public function MovieAssetMaterial(id:*, transparent:Boolean = false, initObject:Object = null)
        {
            super(id, transparent, initObject);
        }
    
        protected override function createBitmap(asset:*):BitmapData
        {
            // Remove previous bitmap
    
            if (this._texture != asset)
            {
                _count[this._texture]--;
    
                var prevMovie:MovieClip = _library[this._texture];
    
                if (prevMovie && _count[this._texture] == 0)
                    _library[this._texture] = null;
            }
    
            // Retrieve from library or...
            var movie:MovieClip = _library[asset];
    
            // ...attachMovie
            if (!movie)
            {
                var MovieAsset:Class = getDefinitionByName(asset) as Class;
                movie = new MovieAsset();
                _library[asset] = movie;
                _count[asset] = 0;
            }
            else
            {
                _count[asset]++;
            }
    
            // Create Bitmap
            return super.createBitmap(movie);
        }
    
        static private var _library:Dictionary = new Dictionary();
        static private var _count:Dictionary = new Dictionary();
    }
}
